var async = require('async');
var AV = require('leanengine');

var ProM = require('../models/product');
var userM = require('../models/modUser');
//购物车相关模型信息

var CartM = AV.Object.extend('CartProduct');
var queryCart = new AV.Query(CartM);

var PackageCartM = AV.Object.extend('JuicePackage');
var queryPackageCart = new AV.Query(PackageCartM);

//商品详情相关模型信息
var ProductM = AV.Object.extend('Product');
var queryPro = new AV.Query(ProductM);

//活动满减相关模型
var ActivityMJM = AV.Object.extend('ActivityRuleMJ');
var queryMJ = new AV.Query(ActivityMJM);

//满送活动相关
var ActivityMSM = AV.Object.extend('ActivityRuleMS');
var queryMS = new AV.Query(ActivityMSM);

module.exports = {

    //删除购物车中商品 !cartproductid:string
    //删除购物车中商品后需要增加库存
    //已完成
    delCartProduct:function(objectid){
        if(objectid){
            var promise = new AV.Promise();
            //根据objectid删除对应的内容
            async.waterfall([
                function(callback){
                    queryCart.get(objectid).then(function(res){
                        callback(null,res);
                    }).catch(function(err){
                        //TODO:错误的处理
                        callback({code:9999,reason:err});
                    });
                },
                function(res,callback){
                    res.destroy().then(function(isSuccess){
                        var addInventory = 0;
                        addInventory = parseInt(isSuccess.get('number') );
                        callback(null,res,addInventory);
                    }).catch(function(err){
                        //TODO:错误的处理
                        callback({code:9999,reason:err});
                    });
                },
                function(res,addInventory,callback){
                    //根据购物车中的pid获取商品表中的记录
                    queryPro.get(res.get('pid')).then(function(info){
                        callback(null, res, info, addInventory);
                    }).catch(function(err){
                        //TODO:错误的处理
                        callback({code:9999,reason:err});
                    });
                },
                function( res, info, addInventory,callback){
                    //增加库存
                    var spec = info.get('spec');
                    var specInfo = spec[res.get('psid')];
                    //历史库存
                    var inventory = specInfo.inventory;
                    //新库存
                    var newInventory = parseInt(inventory) + parseInt(addInventory);
                    inventory = newInventory;
                    specInfo['inventory'] = inventory+'';   //需要将库存转换成string类型
                    info.set('spec',spec);
                    info.save().then(function(){
                        callback(null,{code:0,msg:'删除购物车商品成功'});
                    }).catch(function(err){
                        //TODO:错误的处理
                        callback({code:9999,reason:err});
                    });
                }
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve(result);
                }
            });
            return promise;
        }else{
            return new AV.Promise.error("objectid should not be empty!");
        }
    },

    //立即购买（传入的CID 是否选中为1 修改其他为0）
    //setSingleProductChecked	!cartproductid:string,userid:string 	code:int,msg:string
    //已完成
    setSingleProductChecked:function(objectid,userid){
        if(objectid){
            var promise = new AV.Promise();
            async.waterfall([
                function(callback){
                    //先将个人购物车中的所有数据选中状态变为false：checked=false
                    var queryCart = new AV.Query(CartM);
                    queryCart.equalTo('uid',userid);
                    queryCart.select('id');
                    queryCart.find().then(function(cartList){
                        callback(null, cartList);
                    }).catch(function(err){
                        //TODO:错误的处理
                        callback({code:9999,reason:err});
                    });
                },
                function(cartList,callback){
                    if(!cartList || cartList.length < 1){
                        return callback({code:450,reason:'购物车内没有商品'});
                    }
                    //依次修改所有数据
                    var index = cartList.length;
                    cartList.forEach(function(objid){
                        //var objid = arr.id;
                        //console.log('objid'+objid.id);
                        queryCart.get(objid.id).then(function(res){
                            //console.log(objid.id);
                            //console.log(objectid);
                            if(objid.id == objectid){
                                res.set('checked',true);
                            }else{
                                res.set('checked',false);
                            }
                            res.save().then(function(){
                                index--;
                                if(index == 0){
                                    callback(null,{code:0,msg:'修改成功，直接购买成功'});
                                }
                            }).catch(function(err){
                                //TODO:错误的处理
                                callback({code:9999,reason:err});
                            });
                        }).catch(function(err){
                            //TODO:错误的处理
                            callback({code:9999,reason:err});
                        });
                    });
                }
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve(result);
                }
            });
            return promise;
        }else{
            return new AV.Promise.error("objectid should not be empty!");
        }
    },
    //修改购物车中的数量信息，同时需要变更库存
    setProductQuantity:function(objectid,oldNum,newNum){
        if(objectid){
            var promise = new AV.Promise();
            async.waterfall([
                //首先根据objectid找出对应的数据
                function(callback){
                    queryCart.get(objectid).then(function(res){
                        callback(null,res);
                    }).catch(function(err){
                        //TODO:错误处理
                        callback({code:9999,reason:err});
                    });
                },
                //获取规格中的库存，商品id和规格id以及数量
                function(res,callback){
                    //根据购物车中的pid获取商品表中的记录
                    queryPro.get(res.get('pid')).then(function(info){
                        callback(null, res, info);
                    }).catch(function(err){
                        callback({code:9999,reason:err});
                    });
                },

                //计算差值
                function( res, info, callback){
                    //增加库存
                    var spec = info.get('spec');
                    var specInfo = spec[res.get('psid')];
                    //历史库存
                    var inventory = specInfo.inventory;
                    //新库存
                    var newInventory = parseInt(inventory) - (parseInt(newNum)-parseInt(oldNum)) ;
                    if(newInventory < 0 || isNaN(newInventory)){
                        //如果差值小于0，则表示不能加入购物车，库存不足，返回
                        return callback({code:451,msg:'库存不足'});
                    }
                    inventory = newInventory;
                    specInfo['inventory'] = inventory+'';   //需要将库存转换成string类型
                    info.set('spec',spec);
                    info.save().then(function(){
                        callback(null,res);
                    }).catch(function(err){
                        //TODO:错误的处理
                        callback({code:9999,reason:err});
                    });
                },
                //最后修改库存
                function(res,callback){
                    //变更购物车数量
                    res.set('number',newNum);
                    res.save().then(function(){
                        callback(null,{code:0,msg:'库存修改成功'});
                    }).catch(function(err){
                        callback({code:9999,reason:err});
                    });
                },
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve(result);
                }
            });
            return promise;
        }else{
            return new AV.Promise.error("objectid should not be empty!");
        }
    },

    /**
     * 加入购物车
     * @param pid 产品id
     * @param psid 产品规格id
     * @param num 产品数量
     * @param uid 用户id
     * @auth James 2015-08-28
     */
    insertProToCart:function(pid,psid,num,uid,arg4){
        var mold;
        if(arguments.length < 5){
            mold = '0';
        }else{
            mold = arg4;
        }

        if(!pid) {
            return new AV.Promise.error({code:251});     //商品编号不能为空
        }

        if(!psid) {
            return new AV.Promise.error({code:255});     //商品规格编号不能为空
        }

        if(!num) {
            return new AV.Promise.error({code:256});     //商品数量不能为空
        }

        if(!uid) {
            return new AV.Promise.error({code:250});     //用户编号不能为空
        }

        var promise = new AV.Promise();

        //创建购物车的查询实例
        var query = new AV.Query(CartM);

        async.waterfall([
            function(callback){
                //根据pid,psid,uid获取该对象
                query.equalTo('pid',pid+"");
                query.equalTo('psid',psid+"");
                query.equalTo('uid',uid+"");
                query.first().then(function(res){
                    callback(null,res);
                }).catch(function(err){
                    callback({code:9999,reason:err});    //code:9999 系统错误
                });
            },
            function(res,callback){
                if(!res || res.length<1){
                    //用户之前没有添加该商品到购物车
                    var obj = new CartM();
                    obj.set('number',parseInt(num));
                    obj.set('uid',uid+"");
                    obj.set('pid',pid+"");
                    obj.set('checked',true);
                    obj.set('mold',mold);
                    obj.set('psid',psid+"");
                    obj.save().then(function(cartPro){
                        callback(null,{code:0,objectId:cartPro.id});       //添加购物车成功
                    }).catch(function(err){
                        callback({code:9999,reason:err});//code:9999 系统错误
                    });
                }else{
                    //用户之前已经添加过该商品到购物车
                    res.set('number',parseInt(num)+res.get('number'));
                    res.save().then(function(cartPro){
                        callback(null,{code:0,objectId:cartPro.id,numbser:num});       //添加购物车成功,返回numbser：添加的数量
                    }).catch(function(err){
                        callback({code:9999,reason:err});//code:9999 系统错误
                    });
                }
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },

    //判断是否下架，下架删除商品
    getProductStatus:function(objectid){
        if(objectid){
            var promise = new AV.Promise();
            async.waterfall([
                function(callback){
                    queryCart.get(objectid).then(function(res){
                        var pid = res.get('pid');
                        callback(null,res,pid);
                    }).catch(function(err){
                        //TODO:错误的处理
                        callback(err);
                        //promise.resolve({code:-1,msg:'出错了',err:err});
                    });
                },
                function(res,pid,callback){
                    queryPro.get(pid).then(function(post){
                        var status = post.get('status');
                        callback(null,res,status);
                    }).catch(function(err){
                        //TODO:错误的处理
                        callback(err);
                    });
                },
                function(res,status,callback){
                    //状态为0，则已下架，从购物车中删除该商品
                    if(parseInt(status)==0){
                        res.destroy().then(function(post){
                            callback(null,{code:1,msg:'删除成功'});
                        }).catch(function(err){
                            //TODO:错误的处理
                            callback(err);
                        });
                    }else{
                        callback(null,{code:0,msg:'商品正在销售中，可以购买'});
                    }
                }
            ],function(err,result){
                if(err){
                    promise.reject({code:-2,msg:'删除下架商品失败',err:err});
                }else{
                    promise.resolve(result);
                }
            });
            return promise;
        }else{
            return new AV.Promise.error("objectid should not be empty!");
        }
    },

    // 商品选中修改数据是否选中
    // setProductChecked
    // !cartproductid:string,!checked:boolean
    // code:int,msg:string
    setProductChecked:function(objectid,checked){
        if(objectid){
            var promise = new AV.Promise();
            async.waterfall([
                function(callback){
                    queryCart.get(objectid).then(function(res){
                        callback(null,res);
                    }).catch(function(err){
                        //TODO:错误的处理
                        callback({code:9999,reason:err});
                    });
                },
                function(res,callback){
                    //是否选中
                    res.set('checked',checked);
                    res.save().then(function(post){
                        callback(null, {code:0,msg:'修改成功'});
                    }).catch(function(err){
                        //TODO:错误的处理
                        callback({code:9999,reason:err});
                    });
                }
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve(result);
                }
            });
            return promise;
        }else{
            return new AV.Promise.error("objectid should not be empty!");
        }
    },

    //查询用户的购物车数据
    // getProductList	!userid:String	array<CartProduct购物车数据
    getProductList:function(userid,checked){
        if(userid){
            var promise = new AV.Promise();
            async.waterfall([
                function(callback){
                    var queryCart = new AV.Query(CartM);
                    queryCart.equalTo('uid',userid);
                    if(checked==true){
                        queryCart.equalTo('checked',checked);
                    }
                    queryCart.find().then(function(cartList){
                        callback(null, cartList);
                    }).catch(function(err){
                        callback({code:9999,reason:err});
                    });
                },
                function(cartList,callback){
                    if(!cartList || cartList.length<1){
                        //购物车内没有数据
                          callback(null, {code:0,rows:0,data:{}});
                    }
                    var index = cartList.length;
                    async.eachSeries(cartList,function(each,callback1){
                        queryPro.get(each.get('pid')).then(function(product){
                            each.set('product',product);
                            callback1(null, cartList);

                        }).catch(function(err){
                            callback({code:9999,reason:err});
                        });
                    },function(){
                        callback(null, {code:0,rows:cartList.length,data:cartList});
                    });
                }
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve(result);
                }
            });
            return promise;
        }else{
            return new AV.Promise.error("userid should not be empty!");
        }
    },

    //查询用户的套餐购物车数据
    getPackageProductList:function(userid){
        if(userid){
            var promise = new AV.Promise();
            async.waterfall([
                function(callback){
                    var queryPackageCart = new AV.Query(PackageCartM);
                    queryPackageCart.equalTo('uid',userid);

                    queryPackageCart.find().then(function(cartList){
                        callback(null, cartList);
                    }).catch(function(err){
                        callback({code:9999,reason:err});
                    });
                },
                function(cartList,callback){
                    if(!cartList || cartList.length<1){
                        //购物车内没有数据
                        callback(null, {code:0,rows:0,data:{}});
                    }
                    var index = cartList.length;
                    async.eachSeries(cartList,function(each,callback1){
                        queryPro.get(each.get('pid')).then(function(product){
                            each.set('product',product);
                            callback1(null, cartList);

                        }).catch(function(err){
                            callback({code:9999,reason:err});
                        });
                    },function(){
                        callback(null, {code:0,rows:cartList.length,data:cartList});
                    });
                }
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve(result);
                }
            });
            return promise;
        }else{
            return new AV.Promise.error("userid should not be empty!");
        }
    },

    //读取全场满减规则是否满足返回优惠金额
    // getActivityRuleMJ
    // !货物总价ProductAmount:Double
    // code:int,discountPrice优惠金额:double，msg优惠内容:string
    getActivityRuleMJ:function(productAmount){
        if(productAmount>=0){
            var promise = new AV.Promise();
            //满足价格，选出满足最低价格的
            async.waterfall([
                //第一步：查出所有活动详情
                function(callback){
                    //获取有效时间内的活动
                    var now = new Date();
                    var queryMJ = new AV.Query(ActivityMJM);
                    queryMJ.greaterThanOrEqualTo('endtime',now);
                    queryMJ.lessThanOrEqualTo('starttime',now);
                    queryMJ.ascending('ifprice');
                    queryMJ.find().then(function(activityInfo){
                        callback(null,activityInfo);
                    }).catch(function(err){
                        //TODO:错误的处理
                        callback({code:9999,reason:err});
                    });
                },
                //第二步：将价格与活动中的价格比较，选出最大的优惠
                function(activityInfo,callback){
                    if(!activityInfo || activityInfo.length<1){
                        return callback(null,{code:0,msg:'没有优惠活动',discountPrice:0,ruleList:[]});
                    }
                    var actInfoLength = activityInfo.length;
                    var ruleList = new Array();
                    var rule =[] ;
                    var index = 0 ;
                    activityInfo.forEach(function(post){
                        actInfoLength--;
                        if((productAmount - post.get('ifprice'))>=0){
                            //满足条件后返回，执行回调.
                            //向记录中增加一个checked状态
                            rule = post;
                            index++;
                        }
                        post.set('checked',false);
                        ruleList.push(post);
                        if(actInfoLength==0){
                            if(index>0){
                                ruleList[index-1].set('checked',true);
                            }
                            var discountPrice = 0;
                            if(!(!rule || rule.length<1)){
                                rule.set('checked',true);
                                discountPrice = rule.get('saleprice');
                            }
                            callback(null,{code:0,msg:'成功',discountPrice:discountPrice,ruleList:ruleList,rule:rule});
                        }
                    });
                }
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve(result);
                }
            });
            //promise.resolve({code:1});
            return promise;
        }else{
            return new AV.Promise.error("productAmount should not be empty!");
        }
    },


    //读取全场满送规则是否满足
    //getActivityRuleMS	!货物总价ProductAmount:Double	code:int,msg:string
    getActivityRuleMS:function(productAmount,userid){
        //auto方法
        var promise = new AV.Promise();
        var now = new Date();
        async.auto({
            //判断是否为新用户
            isNewBuyer:function(callback){
                userM.isNewBuyer(userid).then(function(res){
                    callback(null, {code:res.code,msg:res.msg});
                }).catch(function(err){
                    callback(null, err);
                });
            },
            getAllRules:['isNewBuyer',function(callback,results){
                var queryMS = new AV.Query(ActivityMSM);
                queryMS.greaterThanOrEqualTo('endtime',now);
                queryMS.lessThanOrEqualTo('starttime',now);
                queryMS.ascending('ifprice');
                if(results.isNewBuyer.code === 0){
                    //是新用户
                    queryMS.equalTo('type',1);
                }else{
                    queryMS.equalTo('type',0);
                }
                queryMS.find().then(function(activityInfo){
                    callback(null,activityInfo );
                }).catch(function(err){
                    callback({code:9999,reason:err});
                });
            }],
            getCartProEq2:function(callback){
                var queryCart = new AV.Query(CartM);
                queryCart.equalTo('mold','2');
                queryCart.equalTo('uid',userid);
                queryCart.select('id');
                queryCart.first().then(function(proMS){
                    callback(null,proMS);
                }).catch(function(err){
                    callback({code:9999,reason:err});
                });
            },
            //判断购物车内是否有mold=2的商品
            isHasMoldEq2:['getCartProEq2',
                function(callback,results){
                    if((!results.getCartProEq2 ||results.getCartProEq2.length <1 )){
                        callback(null,false);
                    }else{
                        callback(null,true);
                    }
                }
            ],
            //判断是否有活动
            isHasActivities:['getAllRules','isHasMoldEq2',
                function(callback,results){
                    if((!results.getAllRules ||results.getAllRules.length < 1) ){
                        //如果没有活动，需要将购物车内的mold为2的商品删除
                        if(results.isHasMoldEq2){
                            results.getCartProEq2.destroy().then(function(){
                                //console.log('删除成功');
                                callback(null, false);
                            }).catch(function(err){
                                callback({code:9999,reason:err});
                            });
                        }else{
                            callback(null, false);
                        }

                    }else{
                        callback(null,true);
                    }
                }
            ],
            getRule:['isHasActivities','getCartProEq2','isHasMoldEq2',
                function(callback,results){
                    if(!results.isHasActivities ){
                        callback({code:453,reason:'没有满送活动'});
                    }
                    var actInfoLength = results.getAllRules.length;
                    var ruleList = new Array();
                    var rule=new Array();
                    var index = 0;
                    results.getAllRules.forEach(function(post){
                        actInfoLength--;
                        if((productAmount - post.get('ifprice'))>=0){
                            //满足条件后返回，执行回调.
                            index++;
                            rule = post;
                        }
                        post.set('checked',false);
                        ruleList.push(post);
                        if(actInfoLength==0 ){
                            //var resultInfo =  {code:1,msg:ruleList[ruleList.length-1].get('name'),discountPrice:ruleList[ruleList.length-1].get('saleprice'),ruleList:ruleList}
                            if(index>0){
                                ruleList[index-1].set('checked',true);
                                rule.set('checked',true);
                            }
                            //console.log(rule);
                            /*if(index>0){
                                ruleList[index-1].set('checked',true);
                            }*/
                            if(!(!rule || rule.length<1)){
                                rule.set('checked',true);
                            }
                            return callback(null,{code:0,rule:rule,ruleList:ruleList});
                        }
                    });
                }
            ],
            //判断是否有满足条件的rule
            isHasRule:['getRule',
                function(callback,results){
                    if(results.getRule.rule!=null && results.getRule.rule!=''){
                        callback(null,{hasRule:true,rule:results.getRule.rule});
                    }else{
                        callback(null,{hasRule:false,rule:results.getRule.rule});
                    }
                }
            ],
            //判断当前满足条件的pid和psid是否和购物车中的pid和psid相同
            //判断是否需要删除、添加记录
            isNeedDeleteOrAddPro:['isHasRule','isHasMoldEq2',
                function(callback,results){
                    if(results.isHasMoldEq2){
                        if(results.isHasRule.hasRule){
                            var oldPro = results.getCartProEq2;
                            var newPro = results.isHasRule.rule;
                            if(oldPro.get('pid')===newPro.get('pid') && oldPro.get('psid')===newPro.get('psid')){
                                //不执行删除操作，并且不执行添加
                                callback(null,{needDelete:false,needAdd:false});
                            }else{
                                //执行删除操作，并且执行添加
                                callback(null,{needDelete:true,needAdd:true});
                            }
                        }else{
                            //执行删除，但不执行添加
                            callback(null,{needDelete:true,needAdd:false,msg:'不满足条件'});
                        }
                    }else{
                        if(results.isHasRule.hasRule){
                            //不执行删除，但执行添加
                            callback(null,{needDelete:false,needAdd:true,msg:'满足条件,但购物车没商品'});
                        }else{
                            //不执行删除，也不执行添加
                            callback(null,{needDelete:false,needAdd:false,msg:'不满足条件,且购物车没商品'});
                        }
                    }
                }
            ],
            //进行删除和添加操作
            //先删除
            deleteMoldEql2:['isNeedDeleteOrAddPro',
                function(callback,results){
                    if(results.isNeedDeleteOrAddPro.needDelete){
                        results.getCartProEq2.destroy().then(function(){
                            callback(null,true);
                        }).catch(function(err){
                            callback({code:9999,reason:err});
                        });
                    }else{
                        callback(null,true);
                    }
                }
            ],
            //再添加
            addMoldEql2:['deleteMoldEql2',
                function(callback,results){
                    if(results.isNeedDeleteOrAddPro.needAdd){
                        //添加
                        var query = new CartM();
                        query.set('pid',results.getRule.rule.get('pid'));
                        query.set('psid',results.getRule.rule.get('psid'));
                        query.set('number',parseInt(results.getRule.rule.get('number')));
                        query.set('mold','2');
                        query.set('checked',true);
                        query.set('uid',userid);
                        query.save().then(function(newInfo){
                            callback(null,true);
                        }).catch(function(err){
                            callback({code:9999,reason:err});
                        });
                    }else{
                        callback(null,'添加成');
                    }
                }
            ],
            lastFunction:['addMoldEql2',
                function(callback,results){
                    callback(null,{code:1,msg:'终于成功了',ruleList:results.getRule.ruleList});
                }
            ],

        },function(err,results){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(results.lastFunction);
            }
        });
        return promise;
    },
    //查询购物车被选中商品货物总价
    // getGoodsPrice	!userid:String	code:int,msg:string,GoodsPrice货物总价:double
    getGoodsPrice:function(userid){
        if(userid){
            var promise = new AV.Promise();
            async.waterfall([
                function(callback){
                    var queryCart = new AV.Query(CartM);
                    queryCart.equalTo('uid',userid);
                    queryCart.equalTo('checked',true);
                    //排除满送商品
                    queryCart.notEqualTo('mold','2');
                    //queryCart.notContainedIn('mold',['2','4']);
                    queryCart.find().then(function(res){
                        callback(null, res);
                    }).catch(function(err){
                        callback({code:9999,reason:err});
                    });
                },
                function(res,callback){
                    //遍历每条记录，根据商品id和规格id获取价格，再用价格*数量，得到总价
                    if(!res || res.length<1){
                        return callback(null,{code:0,msg:'购物车没有选中商品',GoodsPrice:0,mold:0});
                    }
                    var amount = 0;
                    var wmamount=0; //外卖订单金额
                    var mold = '0';
                    var index = res.length;
                    res.forEach(function(info){

                        queryPro.get(info.get('pid')).then(function(proInfo){
                            var spec = proInfo.get('spec');
                            var psid = spec[info.get('psid')];
                            var price = psid['grprice'];

                            //加入外卖商品不参与满送活动
                            var cid=proInfo.get('cid');
                            var takeoutarray=global.initData.takeout.takeout;
                            if(takeoutarray.indexOf(cid)!=-1){
                                wmamount=wmamount + info.get('number') * price;
                            }


                            if(info.get('mold') == '4'){
                                mold = '4';
                            }

                            amount =amount + info.get('number') * price;
                            index--;
                            if(index === 0){
                                callback(null, {code:1,msg:'查询商品总价成功',GoodsPrice:amount,WaiMaiPrice:wmamount,mold:mold});
                            }
                        }).catch(function(err){
                            callback({code:9999,reason:err});
                        });
                    });
                }
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve(result);
                }
            })
            return promise;
        }else{
            return new AV.Promise.error("userid should not be empty!");
        }
    },

    /**
     * 清理购物车无效商品数据
     * setProductCheck	!uid:int	code:int,msg:string
     * @param userid
     * @returns {AV.Promise.error}
     * 1、删除个人购物车内的无效商品
     * 2、无效商品：pid不存在或者psid不存在或者已下架商品,mold为'4'的商品
     */
    setProductCheck:function(userid){
        if(userid){
            var promise = new AV.Promise();
            //根据uid查找出所有购物车内的商品，然后遍历
            async.waterfall([
                function(callback){
                    var query = new AV.Query(CartM);
                    query.equalTo('uid',userid);
                    query.find().then(function(cartProList){
                        callback(null, cartProList);
                    }).catch(function(err){
                        callback({code:454,reason:'用户购物车没有商品'});
                    });
                },
                function(cartProList,callback){
                    var index = cartProList.length;
                    var delectArray = new Array();
                    var array = new Array();
                    if(!cartProList || cartProList.length<1){
                        return callback({code:455,msg:'用户购物车没有商品'});
                    }
                    async.eachSeries(cartProList,function(cartPro,callback1){
                        var pid = cartPro.get('pid');
                        var psid = cartPro.get('psid');
                        var mold = cartPro.get('mold');
                        var number = cartPro.get('number');
                        if(mold === '4'){
                            delectArray.push({pid:pid,psid:psid,isResInventroy:1,number:number});
                        }
                        var query = new AV.Query(ProductM);
                        //先判断pid是否存在
                        //console.log(pid);
                        query.equalTo('objectId',pid+'');
                        query.equalTo('status',1);
                        query.count().then(function(count){
                            if(count<1){
                                delectArray.push({pid:pid,psid:psid,isResInventroy:0,number:number});
                            }else{
                                array.push({pid:pid, psid:psid,isResInventroy:0,number:number});
                            }
                            callback1(null, {delectArray:delectArray,array:array,cartProList:cartProList});
                        }).catch(function(err){
                            callback(err);
                        });
                    },function(){
                        callback(null, {delectArray:delectArray,array:array,cartProList:cartProList});
                    });
                },
                function(isDelete,callback){
                    var array = isDelete.array;
                    var cartProList = isDelete.cartProList;
                    var delectArray = isDelete.delectArray;
                    var  index = array.length;
                    var delObjectId = new Array();
                    if(!array || array.length<1){
                        return callback(null, {delectArray:delectArray,delObjectId:delObjectId});
                    }
                    async.eachSeries(array,function(info,callback1){
                        var psid = info.psid;
                        var pid = info.pid;
                        var query = new AV.Query(ProductM);
                        //先判断pid是否存在
                        query.get(pid).then(function(pro){
                            var spec = pro.get('spec');
                            if(spec.hasOwnProperty(psid)){
                                //console.log('s');
                            }else{
                                //规格id不存在，则添加到数组中，准备删除
                                delObjectId.push({pid:pid,psid:psid});
                            }
                            callback1(null,{delectArray:delectArray,delObjectId:delObjectId});
                        }).catch(function(err){
                            callback({code:9999,reason:err});
                        });
                    },function(){
                        callback(null, {delectArray:delectArray,delObjectId:delObjectId});
                    });
                },
                function(deleteAll,callback){
                    //删除数据。
                    var deleteInfoByPid = deleteAll.delectArray;
                    var deleteInfoByPsid = deleteAll.delObjectId;
                    var deletePid = new Array();
                    if(!deleteInfoByPid || deleteInfoByPid.length<1){
                        return callback(null, deleteInfoByPsid,deletePid);
                    }
                    var index = deleteInfoByPid.length;
                    async.eachSeries(deleteInfoByPid,function(cartPro,callback1){
                        var query = new AV.Query(CartM);
                        query.equalTo('uid',userid);
                        query.equalTo('pid',cartPro.pid);
                        query.equalTo('psid',cartPro.psid);
                        query.first().then(function(res){
                            if(!res){
                                callback1(null,deletePid );
                            }else{
                                if(res.get('mold')=='4'){
                                    deletePid.push(cartPro);
                                }
                                res.destroy().then(function(res){
                                    callback1(null, deletePid);
                                }).catch(function(err){
                                    callback1(err);
                                });
                            }
                        });
                    },function(){
                       callback(null, deleteInfoByPsid,deletePid) ;
                    });
                },
                //恢复库存
                function(deleteInfoByPsid,deletePid,callback){
                    //console.log((deletePid.length));
                    if(!(!deletePid ||deletePid.length<1)){
                        //恢复库存pid,psid,updateNum
                        async.eachSeries(deletePid,function(eachCartPro,callback1){
                            //判断是否恢复库存
                            if(eachCartPro.isResInventroy === 1){
                                ProM.updateInventory(eachCartPro.pid,eachCartPro.psid,eachCartPro.number).then(function(res){
                                    callback1(null, res);
                                }).catch(function(err){
                                    callback1(null, err);
                                });
                            }else{
                                callback1(null, {msg:''});
                            }
                        },function(){
                            callback(null,deleteInfoByPsid );
                        });
                    }else{
                        callback(null,deleteInfoByPsid);
                    }
                },
                function(deleteInfoByPsid,callback){
                    //删除数据。
                    if(!deleteInfoByPsid || deleteInfoByPsid.length<1){
                        callback(null, {code:0,reason:'没有要删除的数据1'});
                    }
                    var index = deleteInfoByPsid.length;
                    deleteInfoByPsid.forEach(function(cartPro){
                        index--;
                        var query = new AV.Query(CartM);
                        query.equalTo('pid',cartPro.pid);
                        query.equalTo('psid',cartPro.psid);
                        query.first().then(function(res){
                            if(!res || res.length<1){
                                callback(null, {code:1,reason:'没有要删除的数据2'});
                            }
                            res.destroy().then(function(){
                                if(index===0){
                                    callback(null, {code:2,reason:'succcess'});
                                }
                            }).catch(function(err){
                                callback({code:9999,reason:err});
                            });
                        });
                    });
                }
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve(result);
                }
            });
            return promise;
        }else{
            return new AV.Promise.error("userid should not be empty!");
        }
    },
    /**
     * 全选按钮切换
     * @param userid
     * @param checked
     * @returns {*}
     */
    setProductCheckedAll:function(userid,checked){
        var checked=checked;
        if(userid){
            var promise = new AV.Promise();
            //根据uid查找出所有购物车内的商品，然后遍历
            async.waterfall([
                function(callback){
                    var query = new AV.Query(CartM);
                    query.equalTo('uid',userid);
                    query.notEqualTo('mold','2');
                    query.find().then(function(cartProList){
                        callback(null, cartProList);
                    }).catch(function(err){
                        callback({code:456,msg:'用户购物车没有商品'});
                    });
                },
                function(cartProList,callback){
                    var index = cartProList.length;
                    for(var i = 0; i<index;i++){
                        cartProList[i].set('checked',checked);
                        cartProList[i].save().then(function(){
                            if(i===index){
                                //console.log('1');
                                callback(null, {code:0,msg:'全选设置成功！'});
                            }
                        }).catch(function(err){
                            callback({code:457,msg:'全选设置失败！',reason:err});

                        });
                    }
                }
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve(result);
                }
            });
            return promise;
        }else{
            return new AV.Promise.error("userid should not be empty!");
        }
    },
    //获取购物车内所有商品的数量
    getAllCountOfCart:function(userid){
        if(userid){
            var promise = new AV.Promise();
            //根据uid查找出所有购物车内的商品，然后遍历
            async.waterfall([
                function(callback){
                    var query = new AV.Query(CartM);
                    query.equalTo('uid',userid);
                    query.notEqualTo('mold','2');
                    query.find().then(function(cartProList){
                        callback(null, cartProList);
                    }).catch(function(err){
                        callback({code:456,msg:'用户购物车没有商品'});
                    });
                },
                function(cartProList,callback){
                    var index = cartProList.length;
                    var sumNumber = 0;
                    if(!cartProList || index<1){
                        return callback(null, {code:0,sumNumber:sumNumber});
                    }
                    cartProList.forEach(function(cartPro){
                        sumNumber+=parseInt(cartPro.get('number'));
                        index--;
                        if(index===0){
                            //console.log("sumNumber:"+sumNumber);
                            callback(null, {code:0,sumNumber:sumNumber});
                        }
                    });

                }
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve(result);
                }
            });
            return promise;
        }else{
            return new AV.Promise.error("userid should not be empty!");
        }
    },
    /*
     * 订单生成后清除商品数据
     * Add By James 2015-09-10
     * params:userid (用户编号)
     *
     */
    delCart:function(userid){

        if(!userid){
            return new AV.Promise.error({code:458});        //用户编号不能为空
        }

        var promise = new AV.Promise();

        async.waterfall([
            function(callback){
                var queryCart = new AV.Query(CartM);
                queryCart.equalTo('uid',userid);
                queryCart.equalTo('checked',true);
                queryCart.find().then(function(cartList){
                    callback(null, cartList);
                }).catch(function(err){
                    callback({code:9999,reason:err});
                });
            },
            function(cartList,callback){
                if(!cartList || cartList.length<1){
                    //购物车内没有数据
                    callback(null,{code:0});
                }

                cartList.forEach(function (val) {
                    val.destroy().then(function(){

                    }).catch(function(err){
                        callback({code:9999,reason:err});       //code:9999 系统错误
                    });
                });


                callback(null,{code:0});

                //cartList.destroy().then(function(){
                //    callback(null,{code:0});
                //}).catch(function(err){
                //    callback({code:9999,reason:err});       //code:9999 系统错误
                //});
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    /*
     * 订单生成后清除套餐商品数据
     * Add By James 2015-10-13
     * params:userid (用户编号)
     *
     */
    delPackageCart:function(userid){

        if(!userid){
            return new AV.Promise.error({code:458});        //用户编号不能为空
        }

        var promise = new AV.Promise();

        async.waterfall([
            function(callback){
                var queryPackageCart = new AV.Query(PackageCartM);
                queryPackageCart.equalTo('uid',userid);
                queryPackageCart.find().then(function(cartList){
                    callback(null, cartList);
                }).catch(function(err){
                    callback({code:9999,reason:err});
                });
            },
            function(cartList,callback){
                if(!cartList || cartList.length<1){
                    //购物车内没有数据
                    callback(null,{code:0});
                }

                cartList.forEach(function (val) {
                    val.destroy().then(function(){

                    }).catch(function(err){
                        callback({code:9999,reason:err});       //code:9999 系统错误
                    });
                });


                callback(null,{code:0});

                //cartList.destroy().then(function(){
                //    callback(null,{code:0});
                //}).catch(function(err){
                //    callback({code:9999,reason:err});       //code:9999 系统错误
                //});
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
}